package com.dl.code.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dl.code.entity.User;
import com.dl.code.mapper.UserMapper;
import com.dl.code.service.UserService;
import com.dl.code.utils.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * 作者: DL代先生
 * 日期: 2021/5/28
 * 时间: 21:03
 * 内容: Shiro与springboot整合教程！
 * 描述:
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void checkLogin(String account,String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(account,password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
    }

    @Override
    public User selectUserByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",account);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    @Override
    public boolean register(String account, String password) {
        String salt = RandomStringUtils.getString(5);
        System.out.println(salt);
        Md5Hash md5Hash = new Md5Hash(password, salt, 1024);
        String encryption_password = md5Hash.toHex();
        User user = new User();
        user.setUserAccount(account);
        user.setUserSalt(salt);
        user.setUserPassword(encryption_password);
        int insert = userMapper.insert(user);
        if (insert == 1){
            return true;
        }
        return false;
    }
}
